package main

import (
	"bytes"
	"gitee.com/lianyi_work/redis_ope"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gopkg.in/natefinch/lumberjack.v2"
	"io"
	"os"
)

const (
	TASKKEY_TEMPLATE   = "root_dns_config"
	TASKKEY_DOMAINAUTH = TASKKEY_TEMPLATE + ":domain_auth"
)

func init() {
	logger := &lumberjack.Logger{
		// 日志输出文件路径
		Filename: "./log.log",
		// 日志文件最大 size, 单位是 MB
		MaxSize: 100, // megabytes
		// 最大过期日志保留的个数
		MaxBackups: 3,
		// 保留过期文件的最大时间间隔,单位是天
		MaxAge: 28, //days
		// 是否需要压缩滚动日志, 使用的 gzip 压缩
		Compress: true, // disabled by default
	}

	mw := io.MultiWriter(os.Stdout, logger)
	log.SetOutput(mw)

	log.SetReportCaller(true)
	log.SetLevel(log.TraceLevel)
}

func RunRemoteConfig() {
	redis_ope.Connect()
	channel := redis_ope.GetTaskFromRedis(TASKKEY_TEMPLATE)
	go func() {
		for task := range channel {
			log.Tracef("get task: %v", task)
			for task_key, _ := range task {
				config_data, err := redis_ope.GetValue(task_key)
				if err != nil {
					log.Error(err)
					continue
				}

				updateConfig(config_data)
			}
		}
	}()
}

func initConfig() {

}

func updateConfig(config_data string) {
	log.Tracef("get config data: %s", config_data)

	redis_addr := viper.Get("redis_addr")
	redis_auth := viper.Get("redis_auth")

	viper.ReadConfig(bytes.NewBuffer([]byte(config_data)))
	reloadZoneConfig()

	viper.Set("redis_addr", redis_addr)
	viper.Set("redis_auth", redis_auth)
	err := viper.WriteConfig()
	if err != nil {
		log.Error(err)
	} else {
		log.Tracef("restore config file success")
	}
}
